<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="16" class="dataForm">
          <el-col :span="24">
            <el-form-item :label="$t('模板名称')" prop="name">
              <el-input
                v-model="form.name"
                :disabled="['1', '2', '3', '4'].includes(form.id)"
                :placeholder="$t('模板名称')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('公告标题')" prop="title">
              <el-input
                v-model="form.title"
                :placeholder="$t('公告标题')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('在投默认提醒人')" prop="defaultReminder">
              <el-tag
                v-for="tag in splitEmail('defaultReminder')"
                :key="tag"
                closable
                sizi="mini"
                style="margin: 0 2px 0 2px;"
                :disable-transitions="false"
                @close="handleZtClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputZtVisible"
                ref="saveZtTagInput"
                v-model="inputZtValue"
                class="input-new-tag"
                style="width: 20vh;"
                size="mini"
                @keyup.enter.native="handleInputConfirmZt"
                @blur="handleInputConfirmZt"
              />
              <div v-if="userZtVisible" v-loading="!isEmpty(inputZtValue)" class="emailUserSelect">
                <UserSelect
                  v-model="inputZtValue"
                  @change="handleInputConfirmZt('user')"
                />
              </div>
              <el-dropdown v-if="!inputZtVisible && !userZtVisible" trigger="click" @command="handleZtCommand">
                <span class="el-dropdown-link">
                  <i class="el-icon-circle-plus" style="cursor: pointer" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="choice">{{ $t('内部选择') }}</el-dropdown-item>
                  <el-dropdown-item command="input">{{ $t('手动添加') }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('潜在默认提醒人')" prop="defaultQzReminder">
              <el-tag
                v-for="tag in splitEmail('defaultQzReminder')"
                :key="tag"
                closable
                sizi="mini"
                style="margin: 0 2px 0 2px;"
                :disable-transitions="false"
                @close="handleQzClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputQzVisible"
                ref="saveQzTagInput"
                v-model="inputQzValue"
                class="input-new-tag"
                style="width: 20vh;"
                size="mini"
                @keyup.enter.native="handleInputConfirmQz"
              />
              <div v-if="userQzVisible" v-loading="!isEmpty(inputQzValue)" class="emailUserSelect">
                <UserSelect
                  v-model="inputQzValue"
                  @change="handleInputConfirmQz('user')"
                  @blur="handleInputConfirmQz('user')"
                />
              </div>
              <el-dropdown v-if="!inputQzVisible && !userQzVisible" trigger="click" @command="handleQzCommand">
                <span class="el-dropdown-link">
                  <i class="el-icon-circle-plus" style="cursor: pointer" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="choice">{{ $t('内部选择') }}</el-dropdown-item>
                  <el-dropdown-item command="input">{{ $t('手动添加') }}</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-form-item>
          </el-col>
          <el-col v-if="!isEmpty(form.businessId)" :span="24">
            <el-form-item :label="$t('公告模板')" prop="type">
              <div style="display: flex;">
                <!-- 不要加clearable, 如果不选中, 保存的时候没法获取类型, 处理起来会很麻烦, 如果非要改, 从父组件传个参数进来,后台写个变量接收这个类型, 这样就可以在保存的时候删除旧的 -->
                <el-select v-model="form.fileTemplateId" style="width: 92% !important;" filterable :placeholder="$t('请选择')">
                  <el-option
                    v-for="item in templateFileOptions"
                    :key="item.id"
                    :label="$t(item.fileName)"
                    :value="item.id"
                  />
                </el-select>
                <el-button #append icon="el-icon-view" :disabled="!form.fileTemplateId" @click="viewFile" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('公告内容')" prop="context">
              <EditorTxt ref="editorText" v-model="form.context" :height="400" />
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="8">
          <div class="area-header">
            <span class="area-header-title">{{ $t('关键字列表') }}</span>
          </div>
          <el-table :data="keywordList" border class="mb-20">
            <el-table-column :label="$t('名称')" align="center" prop="dictLabel" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                【{{ scope.row.dictLabel }}】
              </template>
            </el-table-column>
            <el-table-column :label="$t('操作')" fixed="right" align="center" class-name="small-padding fixed-width" width="50">
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="text"
                  @click="addKeyWork(scope.row.dictLabel)"
                >{{ $t('插入') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button v-hasPermi="['lp:LpPublicBulletin:edit']" type="primary" @click="submitForm">{{ $t("保存") }}</el-button>
    </div>

    <OnlinePreview ref="OnlinePreview" />
  </div>
</template>

<script>
import EditorTxt from '@/components/Tinymce'
import userSelect from '@/components/UserSelect/user.vue'
import { getLpAnnouncementTemplate, saveLpAnnouncementTemplate } from '@/api/fund/lpBase/lp/affiche/afficheListTemplate.js'
import { getUser } from '@/api/system/user'
import {
  getBusinessWordCustomTemplate,
  listWordOnlineTemplate,
  saveWordSetCustomTemplate
} from '@/api/system/word/template/wordOnlineTemplate'
export default {
  components: {
    EditorTxt,
    userSelect
  },
  props: {
    parentTemplateType: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      // 表单参数
      form: {
        defaultReminder: '',
        defaultQzReminder: ''
      },
      templateFileOptions: [],
      // 遮罩层
      loading: false,
      defaultTemplateMap: { 'callMoney': 'JJCALLKTZ', 'fundFpMain': 'JJFPTZ' },
      // 表单校验
      rules: {
        name: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        title: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        context: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      // 关键字
      keywordList: [],
      inputZtVisible: false,
      inputQzVisible: false,
      userZtVisible: false,
      userQzVisible: false,
      inputZtValue: '',
      inputQzValue: ''
    }
  },
  created() {
    this.getDicts('lp_poster_keywords').then(response => {
      this.keywordList = response.data
    })
    // 模板文件下拉
    listWordOnlineTemplate({ templateType: this.defaultTemplateMap[this.parentTemplateType] }).then(response => {
      this.templateFileOptions = response.rows
    })
  },
  methods: {
    // 初始化数据
    init(data) {
      if (data != null && data.id !== undefined) {
        this.loading = true
        getLpAnnouncementTemplate(data.id).then(response => {
          this.form = response.data
          if (this.isEmpty(this.form.defaultReminder)) {
            this.form.defaultReminder = ''
          }
          this.$refs.editorText.setContent(this.form.context)
          // 加载选中的模板文件
          if (!this.isEmpty(this.form.businessId)) {
            getBusinessWordCustomTemplate(this.form.businessId, this.defaultTemplateMap[this.parentTemplateType]).then(response2 => {
              if (response2.data) {
                this.form.fileTemplateId = response2.data.templateId
              }
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.loading = false
          }
        })
      } else {
        this.reset()
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        fileTemplateId: undefined,
        name: undefined,
        title: undefined,
        defaultReminder: '',
        defaultQzReminder: '',
        selected: 'USER_CREATION',
        context: undefined,
        createTime: undefined,
        createBy: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.templateOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 刷新list页面
      if (this.$parent.$parent.formOpen) {
        this.$parent.$parent.getList()
      }
      // 关闭form页面
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.templateOpen = false
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveLpAnnouncementTemplate(this.form).then(response => {
            if (response.code === 200) {
              // 保存完表单后在保存模板文件
              if (!this.isEmpty(this.form.businessId) && !this.isEmpty(this.form.fileTemplateId) && !this.isEmpty(this.parentTemplateType)) {
                var data = {
                  businessId: this.form.businessId,
                  businessType: 'fund',
                  templateId: this.form.fileTemplateId,
                  templateType: this.defaultTemplateMap[this.parentTemplateType]
                }
                saveWordSetCustomTemplate(data).then(() => {
                  this.msgSuccess(this.$t('保存成功'))
                  this.closeForm()
                }).catch(() => {
                  this.closeForm()
                })
              } else {
                this.closeForm()
              }
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 插入关键字
    addKeyWork(value) {
      this.$refs.editorText.addEditorKeyWord('【' + value + '】')
    },
    // 格式化邮箱显示
    splitEmail(field) {
      if (this.isEmpty(this.form[field])) {
        this.form[field] = ''
        return ''
      }
      return this.form[field].split(';')
    },
    handleZtClose(tag) {
      var lpEmail = this.form.defaultReminder.split(';')
      lpEmail.splice(lpEmail.indexOf(tag), 1)
      if (lpEmail.length === 0) {
        this.$set(this.form, 'defaultReminder', '')
      } else {
        this.$set(this.form, 'defaultReminder', lpEmail.join(';'))
      }
    },
    handleQzClose(tag) {
      var lpEmail = this.form.defaultQzReminder.split(';')
      lpEmail.splice(lpEmail.indexOf(tag), 1)
      if (lpEmail.length === 0) {
        this.$set(this.form, 'defaultQzReminder', '')
      } else {
        this.$set(this.form, 'defaultQzReminder', lpEmail.join(';'))
      }
    },
    handleZtCommand(command) {
      if (command === 'input') {
        this.inputZtVisible = true
        this.$nextTick(() => {
          this.$refs.saveZtTagInput.$refs.input.focus()
        })
      }
      if (command === 'choice') {
        this.userZtVisible = true
      }
    },
    handleQzCommand(command) {
      if (command === 'input') {
        this.inputQzVisible = true
        this.$nextTick(() => {
          this.$refs.saveQzTagInput.$refs.input.focus()
        })
      }
      if (command === 'choice') {
        this.userQzVisible = true
      }
    },
    handleInputConfirmZt(type) {
      this.$nextTick(() => {
        if (type === 'user') {
          if (!this.isEmpty(this.inputZtValue)) {
            getUser(this.inputZtValue).then(response => {
              this.inputZtValue = response.data.email
              if (this.isEmpty(this.inputZtValue)) {
                this.msgError(this.$t('未配置邮箱'))
              }
              this.handleInputConfirmZtSub()
            })
          } else {
            this.handleInputConfirmZtSub()
          }
        } else {
          this.handleInputConfirmZtSub()
        }
      })
    },
    handleInputConfirmZtSub() {
      if (this.checkEmail(this.inputZtValue)) {
        if (this.inputZtValue) {
          var arr = this.form.defaultReminder.split(';')
          arr.push(this.inputZtValue)
          arr = arr.filter((item) => !!item)
          this.form.defaultReminder = arr.join(';')
        }
      }
      this.inputZtVisible = false
      this.userZtVisible = false
      this.inputZtValue = ''
    },
    handleInputConfirmQz(type) {
      this.$nextTick(() => {
        if (type === 'user') {
          if (!this.isEmpty(this.inputQzValue)) {
            getUser(this.inputQzValue).then(response => {
              this.inputQzValue = response.data.email
              if (this.isEmpty(this.inputQzValue)) {
                this.msgError(this.$t('未配置邮箱'))
              }
              this.handleInputConfirmQzSub()
            })
          } else {
            this.msgError(this.$t('未配置邮箱'))
            this.handleInputConfirmQzSub()
          }
        } else {
          this.handleInputConfirmQzSub()
        }
      })
    },
    handleInputConfirmQzSub() {
      if (this.checkEmail(this.inputQzValue)) {
        if (this.inputQzValue) {
          var arr = this.form.defaultQzReminder.split(';')
          arr.push(this.inputQzValue)
          arr = arr.filter((item) => !!item)
          this.form.defaultQzReminder = arr.join(';')
        }
      }
      this.inputQzVisible = false
      this.userQzVisible = false
      this.inputQzValue = ''
    },
    // 预览模板文件
    viewFile() {
      var find = this.templateFileOptions.find(obj => obj.id === this.form.fileTemplateId)
      if (find) {
        this.$refs.OnlinePreview.onlinePreviewFile(find.fileId)
      }
    },
    checkEmail(value) {
      var flag = true
      if (value !== undefined && value !== '' && value !== null) {
        // 校验邮箱
          var regEmail = /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/
          if (!regEmail.test(value)) {
            flag = false
            this.msgError(this.$t('无效邮箱'))
          }
      }
      return flag
    }
  }
}

</script>
<style scoped lang="scss">
/deep/.emailUserSelect {
  width: 20vh;
  display: inline-block;
  .el-input--medium .el-input__inner {
    height: 28px;
    line-height: 28px;
  }
}
</style>
